package com.dabay.web.job;
import java.io.File;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.dabay.web.module.News;
import com.dabay.web.service.News_service;
import com.dabay.web.util.ImagesUtil;
import com.dabay.web.util.TimeUtil;
/**
 * 图片同步到本地并压缩
 */
@Component
public class MQInitQuartz_News_Image {
	private final String TEMP_PATH ="/usr/local/nbrs_image/tempFilePath";
	private final String SAVE_PATH ="/usr/local/nbrs_image/imagefile";
	
	private static Logger logger = LoggerFactory.getLogger(MQInitQuartz_News_Image.class);

	@Autowired
	private News_service news_service;

	@Scheduled(cron = "0 05 1 ? * *")
	public void runFunction() {
		logger.info("图片同步开始推送--> begin ===========");
		sendMQsms();
		logger.info("图片同步推送 结束--> end===========");
	}

	private void sendMQsms() {
		int  thisNewImage =0;
		List<News> newsList= null;
		int twoMonthValue = new TimeUtil().getLastTwoMonth();
		try {
			newsList = news_service.selectNewsImageList();
			for (News news : newsList) {
				String imageHttpUrl = news.getDocimage();
				String[] httpArray  = imageHttpUrl.split(";");
				for(String urlString:httpArray){
					String[] filePathArray = urlString.split("/");
					String filename = filePathArray[filePathArray.length-1];	
					String mulu_one = filePathArray[3];
					String mulu_two = filePathArray[4];
					String mulu_three = filePathArray[5];
					String mulu_four = filePathArray[6];
					if(mulu_four.trim().length()==6){
						int dateMonthValue = Integer.parseInt(mulu_four);
						if(dateMonthValue<twoMonthValue){
							continue;
						}
					}
					String realPath = SAVE_PATH+"/"+mulu_one+"/"+mulu_two+"/"+mulu_three+"/"+mulu_four;
					//如果本地已经存在 就跳过 不处理了
					File checkFile =  new File(realPath+"/"+filename);
					if(checkFile.exists()){
						continue;
					}
					//链接有效性检查
					boolean  isValid = ImagesUtil.checkThisUrlExist(urlString);
					if(isValid==false){
						logger.info("跳过无效的图片链接==="+urlString);
						continue;
					}
					//图片扩展名检查
					boolean  entendIsOk = ImagesUtil.checkThisExtendName(filename);
					if(entendIsOk==false){
						logger.info("跳过无效的非法图片==="+urlString);
						continue;
					}
					thisNewImage++;
					//下载图片到本地
					ImagesUtil.download(urlString, filename,TEMP_PATH);
					//压缩到指定目录中
					File sf=new File(realPath);
					if(!sf.exists()){
					   sf.mkdirs();
					}
					ImagesUtil imagesUtil = new ImagesUtil(TEMP_PATH+"/"+filename,realPath+"/"+filename);
					imagesUtil.resize(400, 600);
					//清空临时目录
					File delteTempFile =  new File(TEMP_PATH+"/"+filename);
					if(delteTempFile.exists()){
						delteTempFile.delete();
					}
				}
			}
		} catch (Exception e) {
			logger.info("fail info  "+e.fillInStackTrace());
			logger.info("error!! loading  zwdt index fail == ");
		}
	}
}
